package com.xiaochong.tir.api.service.walian;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import com.xc.logclient.utils.LogTrace;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaochong.tir.api.component.HbaseBaseQueryComponent;
import com.xiaochong.tir.common.data.hbasepo.DiagnosisMarketPerformance;
import com.xiaochong.tir.common.data.hbasepo.DiagnosisScore;
import com.xiaochong.tir.common.data.mapper.CurrencyInfoMapper;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.vo.walian.WalianCurrencyInfo;
import com.xiaochong.tir.common.data.vo.walian.WalianDiagnosis;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;

/**
 * @author qzw
 * 2018年7月2日 下午4:45:52
 * @description 
 **/
@Service
public class TokenIndexService {

	@Autowired
	private CurrencyInfoMapper currencyInfoMapper;
	
	@Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;

	
	/**
	 * 组装所有诊断货币的折线图和评语
	 */
	public List<WalianDiagnosis> getCurrencyAndComment(){

		LogTrace.beginTrace();
		//查询所有诊断货币
		CurrencyInfo t = new CurrencyInfo();
		t.setDeleteFlag(false);
		t.setEnableFlag(true);
		t.setCurrencyDiagnosisFlag(true);
		List<CurrencyInfo> list = currencyInfoMapper.selectByEntityList(t);
		//存放诊断货币排名，防止重复
		Map<String, String> map = new LinkedHashMap<>();
		//存放所有信息（折线图数据和评语）
		List<WalianDiagnosis> wdList = new ArrayList<>();

		try {

			for(CurrencyInfo c : list){
				//诊断总信息
				WalianDiagnosis wd = new WalianDiagnosis();
				//单个诊断货币的折线图数据（价格和时间）
				List<WalianCurrencyInfo> wciList = new ArrayList<WalianCurrencyInfo>();
				//根据rowKey查询当天货币信息（获取市值，时间）
				String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                        , c.getCmcId() + "@" + DateUtils.getCurrentDateString());
				JSONObject todayMap = new JSONObject();
				if(StringUtils.isNotBlank(data)) todayMap = JSON.parseObject(data);

				//24小时折线图数据
				WalianCurrencyInfo wci =null;
				int s = 0;
				if(!todayMap.isEmpty()){
					for (String key:todayMap.keySet()) {
						if(Integer.valueOf(key) > s){
							s = Integer.valueOf(key);
						}
						JSONArray array = todayMap.getJSONArray(key);
						JSONObject obj = (JSONObject) array.get(array.size()-1);
						wci = new WalianCurrencyInfo();
						wci.setCreateTime(obj.getString("createTime"));
						wci.setPriceCny(obj.getString("priceCny"));
						wciList.add(wci);
					}
				}

				//查询前一天的货币信息（获取市值，时间）
				String yesdata = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                        , c.getCmcId() + "@" + DateUtils.getNextDayDateYMD(-1));
				JSONObject yesMap = new JSONObject();
				if(StringUtils.isNotBlank(yesdata)) yesMap = JSON.parseObject(yesdata);

				if(!yesMap.isEmpty()){
					for (String key:yesMap.keySet()) {
						JSONArray array =yesMap.getJSONArray(key);
						JSONObject obj = (JSONObject) array.get(array.size()-1);
						//如果list中有数据,key必大于零,接着今天的数据取昨天的
						if(Integer.valueOf(key) > s && wciList.size()>0){
							wci = new WalianCurrencyInfo();
							wci.setCreateTime(obj.getString("createTime"));
							wci.setPriceCny(obj.getString("priceCny"));
							wciList.add(wci);
						}else{
							wci = new WalianCurrencyInfo();
							wci.setCreateTime(obj.getString("createTime"));
							wci.setPriceCny(obj.getString("priceCny"));
							wciList.add(wci);
						}
					}
				}

				//加入折线图数据
				wd.setWci(wciList);

				String time = LocalDateTime.now().format(DateUtils.format_ymdhm);
				time = subTime(time);

				String ytime =LocalDateTime.now().minusDays(1).format(DateUtils.format_ymdhm);
				ytime = subTime(ytime);

				//获取货币的排名
				while (true){
					if(time.equals(ytime)){
						break;
					}
					Map<String,Object> resultMap = hbaseBaseQueryComponent.
							selectData(HbaseTableUtils.CURRENCY_INFO_TABLE_NAME, c.getCmcId() + "_" + time);
					if(!resultMap.isEmpty()){
						//设置货币的排名
						setCurrencyInfo(resultMap, wd, map);
						wd.setSymbol(c.getSymbol());
						//设置量能变化、货币流动性、人气意愿指数、市场表现评语
						setCommentInfo(c, wd);
						wdList.add(wd);
						break;
					}else{
						time = String.valueOf(LocalDateTime.parse(time,DateUtils.format_ymdhm).minusMinutes(5).format(DateUtils.format_ymdhm));
					}
				}
			}
			return wdList;
		} catch (HbaseConnectionExcetion | HbaseGetTableExcetion | IOException | HbaseCloseExcetion e) {
			e.printStackTrace();
            return wdList;
		}
	}

	private String subTime(String time) {
		String tm = time.substring(time.length() - 1);
		if(Integer.valueOf(tm) > 0 && Integer.valueOf(tm) < 5){
			time = time.substring(0, time.length() - 1) + "0";
		}else if(Integer.valueOf(tm) > 5 && Integer.valueOf(tm) < 10){
			time = time.substring(0, time.length() - 1) + "5";
		}
		return time;
	}

	/**
	 * 设置折线图数据
	 * @param resultMap
	 * @param wd
	 * @param map
	 */
	public void setCurrencyInfo(Map<String,Object> resultMap, WalianDiagnosis wd, Map<String, String> map){
		String rank = (String)resultMap.get("rank");
		String id = (String) resultMap.get("id");
		if(!map.containsKey(id)){
			map.put(id, rank);
			//加入排名
			wd.setRank(Integer.valueOf(rank));
		}
	}
	
	/**
	 * 设置量能变化、货币流动性、人气意愿指数、市场表现评语
	 * @param c
	 * @param wd
	 */
	public void setCommentInfo(CurrencyInfo c, WalianDiagnosis wd){
		try {
			//获取诊断得分表中量能变化、货币流动性、人气意愿指数评语
			String grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_NAME
			        , HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_FAMILY
			        , HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_QUALIFIER
			        , c.getCmcId()+"@"+DateUtils.getCurrentDateString());

			//今天没有获取昨天
			if(StringUtils.isBlank(grailStr)){
				grailStr = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_NAME
						, HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_FAMILY
						, HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_QUALIFIER
						, c.getCmcId()+"@"+LocalDateTime.now().minusDays(1).format(DateUtils.format_ymds));
			}

			if(StringUtils.isNotBlank(grailStr)){
				Map<String, Object> map = JSON.parseObject(grailStr, Map.class);
				Object obj = map.get(getHour(map) + "");
				JSONArray ja = JSONArray.parseArray(obj.toString());
				JSONObject o = (JSONObject)ja.get(ja.size() - 1);
				DiagnosisScore ds = o.toJavaObject(DiagnosisScore.class);
				wd.setCurrencyLiquidity(ds.getLiquidityComment());
				wd.setEnergyChange(ds.getQuantumEnergyComment());
				wd.setPopularityWill(ds.getPopularityIndicatorComment());
			}

			//货币诊断 趋势分析 市场表现 表中市场表现评语
			String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_NAME
					, HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_FAMILY
					, HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_QUALIFIER
					, c.getCmcId()+"@"+DateUtils.getCurrentDateString());

			if(StringUtils.isBlank(data)){
				data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_NAME
						, HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_FAMILY
						, HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_QUALIFIER
						, c.getCmcId()+"@"+LocalDateTime.now().minusDays(1).format(DateUtils.format_ymds));
			}

			if(StringUtils.isNotBlank(data)){
				Map<String, Object> map2 = JSON.parseObject(data, Map.class);
				//获取小时最大的一组数据
				Object obj2 = map2.get(getHour(map2) + "");
				JSONArray ja2 = JSONArray.parseArray(obj2.toString());
				JSONObject o2 = (JSONObject)ja2.get(ja2.size() - 1);
				DiagnosisMarketPerformance dmp = o2.toJavaObject(DiagnosisMarketPerformance.class);
				wd.setMarketPerformance(dmp.getComment());
			}
		} catch (HbaseConnectionExcetion | HbaseGetTableExcetion | IOException | HbaseCloseExcetion e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取最大的小时
	 * @param map
	 * @return
	 */
	public int getHour(Map<String, Object> map){
		int hour = 0;
		for(String s : map.keySet()){
			if(hour < Integer.valueOf(s)){
				hour = Integer.valueOf(s);
			}
		}
		return hour;
	}
}
